package info.jic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;

public class Display extends JFrame
{
	private static final long serialVersionUID = -640147321302266672L;
	
	private String currentServer;
	private String channel = "#uno";
	private String nick = "Patt_Uno";
	private String server = "irc.thinstack.net";
	private int port = 6667;
	
	PrintWriter pw;

	public Display()
	{
		ChannelTextBox ctb = new ChannelTextBox();
		
		this.add(ctb);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(800,600);
		this.setVisible(true);
		
		try 
		{
			Socket skt = new Socket(server,port);
			BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
			pw = new PrintWriter(skt.getOutputStream(),true);
			
			while(true)
			{
				String str = br.readLine();
				
				
				
				if(str.indexOf("PRIVMSG") != -1 && str.indexOf("!~") != -1)
				{
					ctb.addLine(parseMessage(channel,str));
				}
				else if(str != null)
				{
					ctb.addLine(str);
				}
				
				if(str.indexOf("NOTICE * :*** Looking up your hostname") != -1)
				{
					currentServer = str.substring(1, str.indexOf(" "));
				}
				else if(str.indexOf("Checking Ident") != -1)
				{
					pw.println("NICK "+nick);
					pw.println("USER "+nick+" 8 * : Bot Bot");
				}
				else if(str.indexOf("376") != -1)
				{
					pw.println("JOIN "+channel);
					pw.println("PRIVMSG "+channel+" :Bot Has Connected.");
					//pw.println("QUIT");
				}
				else if(str.indexOf("PING") != -1)
				{
					pw.println("PONG :" + currentServer);
				}
				else if(parseMessageNoNick(channel,str).equals("!hme"))
				{
					sendMsg(channel,"No Help for you!");
				}
			}
		} 
		catch (UnknownHostException e) 
		{
			e.printStackTrace();
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	public String parseMessage(String chan, String msg)
	{
		return "<" + msg.substring(1,msg.indexOf("!")) + "> " + msg.substring(msg.indexOf(chan)+chan.length() + 2);
	}
	
	public String parseMessageNoNick(String chan, String msg)
	{
		try
		{
			System.out.println(msg.substring(msg.indexOf(chan)));
			return msg.substring(msg.indexOf(chan) + chan.length() + 2);
		}
		catch(StringIndexOutOfBoundsException e)
		{
			
		}
		
		return null;
	}
	
	public void sendMsg(String chan, String msg)
	{
		pw.println("PRIVMSG "+chan+" :"+msg);
	}
}
